define(['lib','text!components/tabPage.tpl'], function(LIB,tpl) {
	TabPage = Backbone.Model.extend({
		defaults:{
			id:"NULL",
			title:"TITLE",
			url:""
		}
	});
	TabPageGroup = Backbone.Collection.extend({
		model:TabPage,
		initialize: function(models, options) {
			console.log("init TabPage list");
		},
		parse : function(data) {
			
		}
	});
	TabPageView = Backbone.View.extend({
		el: $("#body-content"),
		template: _.template(tpl),
		initialize: function() {
			this.count = 1;
			this.render();
			this.tabPageGroup = new TabPageGroup(TabPage, {view:this})
		},
		events: {
			"click .tab_remove":"closeTab"
		},
		render: function() {
            this.$el.html(this.template({}));
      	},
      	addTab:function(title,url,icon){
      		console.log("add TabPage");
      		var c = this.tabPageGroup.where({title:title});
      		if(c.length <=0 ){
	      		var tab = new TabPage();
	      		var id = this.getId();
	      		tab.set({id:id,title:title,url:url});
	      		this.tabPageGroup.add(tab);
	      		this.$el.find('#appTab').append('<li><a href="#'+id+'" data-toggle="tab"><i class="icon '+icon+'"></i><span>'+title+'</span><i class="tab_remove">×</i></a></li>');
	      		this.$el.find('#appTabContent').append('<div class="tab-pane fade" id="'+id+'"></div>');
	      		$("#"+id).load(url);
	      		$('#appTab a:last').tab('show');
      		} else {
      			var id = c[0].get('id');
      			$('#appTab a[href="#'+id+'"').tab('show');
      		}
      	},
      	closeTab:function(event){      		
      		var dom = $(event.target).parents('li');
      		var id = $(event.target).parents('a').attr('href').replace('#','');
      		console.log('close-----' +id);
      		var d = this.tabPageGroup.where({id:id});
      		if(d.length>0){
      			this.tabPageGroup.remove(d);
      		}
      		dom.remove();
      		$("#"+id).remove();
      		$('#appTab a:last').tab('show');
      	},
      	getId:function(){
      		return "TAB"+this.count++;
      	}
	});
});